<template>
  <div class="container">
    <el-row :gutter="15">
      <el-form
        ref="questionsFormRef"
        :model="questionsFormData"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
      <el-col class="title">试题录入</el-col>

        <!-- 选择学科 -->
        <el-col :span="24">
          <el-form-item label="学科" prop="subjectID">
            <el-select
              v-model="questionsFormData.subjectID"
              placeholder="请输入学科"
              clearable
              :style="{ width: '40%' }"
              @change="getCatalog"
            >
              <el-option
                v-for="(item, index) in subjectIDOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 选择目录 -->
        <el-col :span="24">
          <el-form-item label="目录" prop="catalogID">
            <el-select
              v-model="questionsFormData.catalogID"
              placeholder="请输入目录"
              clearable
              :style="{ width: '40%' }"
            >
              <el-option
                v-for="item in catalogIDOptions"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 选择企业 -->
        <el-col :span="24">
          <el-form-item label="企业" prop="enterpriseID">
            <el-select
              v-model="questionsFormData.enterpriseID"
              placeholder="请输入企业"
              clearable
              :style="{ width: '40%' }"
            >
              <el-option
                v-for="item in shortNameOptions"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 选择城市 -->
        <el-col :span="24" type="flex">
          <el-form-item label="城市" prop="province">
              <el-col :span="5">
                <el-select
                  v-model="questionsFormData.province"
                  placeholder="请选择"
                  clearable
                  :style="{ width: '100%' }"
                  @change="filterCity"
                >
                  <el-option
                    v-for="(item, index) in provinceOptions"
                    :key="index"
                    :label="item.city"
                    :value="item.city"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="5">
                <el-select
                  v-model="questionsFormData.city"
                  placeholder="请选择"
                  clearable
                  :style="{ width: '95%' }"
                >
                  <el-option
                    v-for="(item, index) in cityOptions"
                    :key="index"
                    :label="item"
                    :value="item"

                  ></el-option>
                </el-select>
              </el-col>
          </el-form-item>
        </el-col>

        <!-- 方向 -->
        <el-col :span="24">
          <el-form-item label="方向" prop="direction">
            <el-select
              v-model="questionsFormData.direction"
              placeholder="请选择方向"
              clearable
              :style="{ width: '40%' }"
            >
              <el-option
                v-for="(item, index) in directionOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 题型 -->
        <el-col :span="24">
          <el-form-item class="question-type" label="题型" prop="questionType">
            <el-radio-group
              v-model="questionType"
              size="medium"
            >
              <el-radio
                v-for="(item, index) in questionTypeOptions"
                :key="index"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- 难度 -->
        <el-col :span="24">
          <el-form-item class="difficulty" label="难度" prop="difficulty">
            <el-radio-group
              v-model="difficulty"
              size="medium"
            >
              <el-radio
                v-for="(item, index) in difficultyOptions"
                :key="index"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- 题干 富文本 -->
        <el-col :span="24">
          <el-form-item style="height: 340px" label="题干" prop="question">
            <quill-editor-quetion
              :question.sync="questionsFormData.question"
            />
          </el-form-item>
        </el-col>
        <!-- 选项 -->
        <el-col :span="24" v-if="questionType !== 3">
          <el-form-item label="选项" prop="options">
              <el-col
                class="options"
                v-for="item in checkOptions"
                :key="item.id"
                >
                    <el-radio
                      v-if="questionType === 1"
                      :label="item.code"
                      v-model="radioValue"
                    >{{ item.code }}：
                    </el-radio>
                    <el-checkbox
                      v-else
                      v-model="checkBoxesValue"
                      :label="item.code"
                    >{{ item.code }}：
                    </el-checkbox>
                  <!-- 输入框 -->
                  <el-input v-model="item.title" :style="{ width: '240px' }" />
                  <!-- 上传组件 -->
                  <el-upload
                    action="http://localhost:7001/"
                    list-type="picture-card"
                    :auto-upload="false"
                  >
                      <span class="upload-text">上传图片</span>
                      <i slot="default" class="el-icon-circle-close"></i>
                  </el-upload>
                </el-col>
              <el-button
              type="danger"
              :disabled="questionType !== 2"
              @click="addCheckOption"
              >+增加选项与答案</el-button>
              <!-- end -->
          </el-form-item>
        </el-col>

        <!-- 解析视频 -->
        <el-col :span="24">
          <el-form-item label="解析视频" prop="videoURL">
            <el-input
              v-model="questionsFormData.videoURL"
              placeholder="请输入解析视频"
              clearable
              :style="{ width: '40%' }"
            ></el-input>
          </el-form-item>
        </el-col>

        <!-- 答案解析 富文本 -->
        <el-col :span="24">
          <el-form-item style="height: 340px" label="答案解析" prop="answer">
            <quill-editor-answer :answer.sync="questionsFormData.answer" />
          </el-form-item>
        </el-col>

        <!-- 题目备注 -->
        <el-col :span="24">
          <el-form-item label="题目备注" prop="remarks">
            <el-input
              v-model="questionsFormData.remarks"
              type="textarea"
              placeholder="请输入题目备注"
              :autosize="{ minRows: 4, maxRows: 4 }"
              :style="{ width: '40%' }"
            ></el-input>
          </el-form-item>
        </el-col>

        <!-- 试题标签 -->
        <el-col :span="24">
          <el-form-item label="试题标签" prop="tags">
             <el-select
                @change="tags2Str"
                v-model="selectedTags"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择"
                :style="{ width: '40%' }"
             >
                <el-option
                  v-for="item in tagsOptions"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.tagName">
                </el-option>
              </el-select>
          </el-form-item>
        </el-col>

        <!-- 提交 -->
        <el-col :span="24">
          <el-form-item size="large">
            <el-button
              v-if="!this.$route.query.id"
              type="primary"
              @click="submitForm"
            >确认提交</el-button>
            <el-button
              v-else
              type="success"
              @click="confirmForm"
            >确认修改</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>

      </el-form>
    </el-row>
  </div>
</template>

<script>

import quillEditorQuetion from '../components/quill-editor-question.vue'
import quillEditorAnswer from '../components/quill-editor-answer.vue'

import { datas } from '../../api/hmmm/citys'
import { direction, difficulty, questionType } from '../../api/hmmm/constants'
import { simple } from '../../api/hmmm/subjects'
import { list as catalogList } from '../../api/hmmm/directorys'
import { list as companyList } from '../../api/hmmm/companys'
import { list as tagList } from '../../api/hmmm/tags'
import { add as addQuestion, update, detail } from '../../api/hmmm/questions'

export default {
  name: 'Questions',
  components: {
    quillEditorQuetion,
    quillEditorAnswer
  },
  props: [],
  data () {
    return {
      questionsFormData: {
        subjectID: undefined,
        catalogID: undefined,
        enterpriseID: undefined,
        province: undefined,
        city: undefined,
        direction: undefined,
        questionType: String(this.questionType),
        difficulty: String(this.difficulty),
        question: undefined,
        options: [],
        videoURL: undefined,
        answer: undefined,
        remarks: undefined,
        tags: ''
      },
      questionType: 1,
      difficulty: 1,
      rules: {
        subjectID: [
          {
            required: true,
            message: '请输入学科',
            trigger: 'change'
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请输入目录',
            trigger: 'change'
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请输入企业',
            trigger: 'change'
          }
        ],
        province: [
          {
            required: true,
            message: '请选择城市',
            trigger: 'change'
          }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向',
            trigger: 'change'
          }
        ],
        questionType: [
          {
            required: true,
            message: '题型不能为空',
            trigger: 'change'
          }
        ],
        difficulty: [
          {
            required: true,
            message: '难度不能为空',
            trigger: 'change'
          }
        ],
        question: [
          {
            required: true,
            message: '题干不能为空',
            trigger: 'change'
          }
        ],
        answer: [
          {
            required: true,
            message: '答案解析不能为空',
            trigger: 'change'
          }
        ],
        tags: [
          {
            required: true,
            message: '试题标签不能为空',
            trigger: 'change'
          }
        ]
      },
      subjectIDOptions: [
        {
          label: '选项一',
          value: 1
        },
        {
          label: '选项二',
          value: 2
        }
      ],
      catalogIDOptions: [
        {
          label: '选项一',
          value: 1
        },
        {
          label: '选项二',
          value: 2
        }
      ],
      shortNameOptions: [
        {
          label: '选项一',
          value: 1
        },
        {
          label: '选项二',
          value: 2
        }
      ],
      provinceOptions: datas,
      cityOptions: [],
      directionOptions: direction,
      questionTypeOptions: questionType,
      difficultyOptions: difficulty,
      // 基础选项
      checkOptions: [
        {
          code: 'A',
          id: 1,
          img: '',
          isRight: 0,
          questionsID: null,
          title: ''
        },
        {
          code: 'B',
          id: 2,
          img: '',
          isRight: 0,
          questionsID: null,
          title: ''
        },
        {
          code: 'C',
          id: 3,
          img: '',
          isRight: 0,
          questionsID: null,
          title: ''
        },
        {
          code: 'D',
          id: 4,
          img: '',
          isRight: 1,
          questionsID: null,
          title: ''
        }
      ],
      tagsOptions: [],
      selectedTags: [],
      addInputValue: '',
      // 选择的选项
      checkBoxesValue: [],
      radioValue: '',
      // 上传图片相关
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  computed: {
  },
  watch: {},
  created () {
    this.getSimpleSubjects()
    this.getCompanys()
    this.getQuestionsDetail()
    console.log(this.$route.query.id)
  },
  methods: {
    // 确认提交
    submitForm () {
      this.$refs.questionsFormRef.validate(async (valid) => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // TODO 提交表单
        await addQuestion(this.questionsFormData)
        this.$message.success('添加成功！')

        // 重置表单
        this.resetForm()
        this.radioValue = ''
        this.checkBoxesValue = []

        this.$router.push('list')
      })
    },
    // 确认修改
    async confirmForm () {
      await update(this.questionsFormData)
      this.$message.success('修改成功！')

      this.resetForm()
      this.radioValue = ''
      this.checkBoxesValue = []

      if (this.$route.query.id === 25) {
        // 跳到基础题库
        this.$router.push('list')
      } else if (this.$route.query.id === 27) {
        // 跳到精选题库
        this.$router.push('choice')
      }
    },
    resetForm () {
      this.$refs.questionsFormRef.resetFields()
    },
    // 上传图片相关
    handleRemove (file) {
      console.log(file)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload (file) {
      console.log(file)
    },
    // 获取基础题库详情
    async getQuestionsDetail () {
      if (this.$route.query.id) {
        const { data } = await detail({
          id: this.$route.query.id
        })
        this.questionsFormData = data

        this.getCatalog()
        this.getTagList()

        this.questionType = Number(data.questionType)
        this.difficulty = Number(data.difficulty)
        this.checkOptions = data.options

        // 显示正确答案
        if (this.questionType === 2) {
          this.checkBoxesValue = data.options.map(item => {
            return item.isRight ? item.code : ''
          })
        } else if (this.questionType === 1) {
          this.radioValue = data.options.map(item => {
            return item.isRight ? item.code : ''
          }).join('')
        }
      }
    },
    // 根据选择的市区挑选出它所属区县
    filterCity () {
      const citys = this.provinceOptions.filter(item => item.city === this.questionsFormData.province)
      this.cityOptions = citys[0].area
    },

    // 获取学科简单列表
    async getSimpleSubjects () {
      const { status, statusText, data } = await simple()
      if (status !== 200) return this.$message.error(statusText)
      this.subjectIDOptions = data
    },

    // 获取目录
    async getCatalog () {
      const { status, data } = await catalogList({
        pagesize: 5000,
        subjectID: this.questionsFormData.subjectID
      })
      if (status !== 200) return this.$message.error('获取数据失败！')
      this.catalogIDOptions = data.items
      this.getTagList()
    },

    // 获取企业列表
    async getCompanys () {
      const { status, data } = await companyList({ pagesize: 5000 })
      if (status !== 200) return this.$message.error('获取数据失败！')
      this.shortNameOptions = data.items
    },

    // 获取标签列表
    async getTagList () {
      const { status, data } = await tagList({
        subjectID: this.questionsFormData.subjectID,
        pagesize: 50
      })
      if (status !== 200) return this.$message.error('获取数据失败！')
      this.tagsOptions = data.items
      // 设置默认选中标签
      this.selectedTags = data.items.map(item => item.tagName)
    },

    // 标签数组转为字符串并赋值给表单data
    tags2Str () {
      this.questionsFormData.tags = this.selectedTags.join(' ')
    },

    // 添加选项
    addCheckOption () {
      const length = this.checkOptions.length
      const option = {
        code: String.fromCharCode(length + 65),
        id: length + 1,
        img: '',
        isRight: 1,
        questionsID: null,
        title: ''
      }
      this.checkOptions.push(option)
    }
  }
}
</script>

<style scoped lang="less">
.container {
  margin: 15px;
  background: #fff;
  overflow: hidden;
  .title {
    margin: 20px 0 15px 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  .el-form {
    clear: both;
    overflow: hidden;
    padding-right: 20px;
    ::v-deep .el-upload {
      width: 100px;
      height: 60px;
      border: 1px initial;
      position: relative;
      .el-icon-plus {
        position: absolute;
      }
    }
    .el-form-item {
      .el-radio {
        margin: 0;
      }
      .col-tags {
        position: absolute;
      }
    }
    .difficulty,
    .question-type {
      ::v-deep .el-radio__label {
        padding: 0 30px 0 0;
      }
    }
    .options {
      padding: 10px 0;
      display: flex;
      align-items: center;
      ::v-deep .el-upload {
        margin-left: 10px;
        font-size: 16px;
        .upload-text {
          position: absolute;
          width: 100%;
          height: 100%;
          top: -80%;
          right: 0;
          font-size: 14px;
        }
        .el-icon-circle-close {
          position: absolute;
          top: 0;
          right: 0;
          transform: translate(50%, -50%);
          background: #fff;
        }
      }
    }
    .el-form-item__content {
      display: flex;
    }
  }
}
</style>
